package com.zsh.weather.ln.https

import com.yechaoa.yutilskt.LogUtilKt
import okhttp3.*
import java.io.IOException

class RequestManager {
    private lateinit var okHttpClient: OkHttpClient
    private var builder: Request.Builder

    init {
        builder = Request.Builder()
    }

    constructor() {
        LogUtilKt.d("RequestManager初始化")
        okHttpClient = HttpManager.instace().httpClient
    }

    constructor(okHttpClient: OkHttpClient?) {
        if (okHttpClient == null) {
            RequestManager()
        } else {
            this.okHttpClient = okHttpClient
        }
    }

    fun doGet(
        url: String,
        headers: HashMap<String, String>? = null,
        params: HashMap<String, String>? = null
    ): RequestManager {
        if (url.isBlank()) return this
        if (headers != null) addHeaders(headers)
        LogUtilKt.d("请求url_:" + setGetParmas(url, params!!))
        builder.url(if (params != null) setGetParmas(url, params) else url).get()
        return this
    }

    fun doPost(
        url: String,
        headers: HashMap<String, String>? = null,
        params: HashMap<String, String>
    ): RequestManager {
        if (url.isBlank()) return this
        if (headers != null) addHeaders(headers)
        builder.url(url)
        builder.post(setPostParams(params))
        return this
    }

    fun addHeaders(headers: HashMap<String, String>) {
        headers.entries.forEach { entry ->
            headers.keys
            builder?.addHeader(entry.key, entry.value)
        }
    }

    fun setGetParmas(url: String, params: HashMap<String, String>): String {
        val sb = StringBuffer(url)
        if (!url.contains("?")) sb.append("?") else sb
        params.entries.forEach { entry ->
            params.keys
            sb.append(entry.key + "=" + entry.value + "&")
        }
        return if (sb.toString().endsWith("&")) sb.toString().subSequence(0, sb.lastIndex)
            .toString() else sb.toString()
    }

    fun setPostParams(params: HashMap<String, String>): RequestBody {
        val builder = FormBody.Builder()
        params.entries.forEach { entry ->
            params.keys
            builder.add(entry.key, entry.value)
        }
        return builder.build()
    }

    fun execute(abstractCallBack: AbstractCallBack) {
        okHttpClient.newCall(builder.build()).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                abstractCallBack.onFailure(call, e)
            }

            override fun onResponse(call: Call, response: Response) {
                abstractCallBack.onResponse(call, response)
            }
        })
    }
}